package com.kk.miaosha.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.BeanProperty;
import com.kk.miaosha.Vo.LoginUser;
import com.kk.miaosha.Vo.UserVo;
import com.kk.miaosha.entity.ItemKill;
import com.kk.miaosha.entity.User;
import com.kk.miaosha.entity.UserRole;
import com.kk.miaosha.exception.CustomException;
import com.kk.miaosha.exception.R;
import com.kk.miaosha.securityEntity.UserDetail;
import com.kk.miaosha.service.ItemKillService;
import com.kk.miaosha.service.RoleMenuService;
import com.kk.miaosha.service.UserRoleService;
import com.kk.miaosha.service.UserService;
import com.kk.miaosha.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author : K k
 * @date : 19:04 2020/10/21
 */
@RestController
@Slf4j
@RequestMapping("user")
@Api(value = "IndexController",description = "登陆注册注销接口")
public class IndexController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @PostMapping("/login")
    public R login(@RequestBody LoginUser user){
        //System.out.println("登陆业务: username:"+user.getUsername()+" 密码："+user.getPassword());
        Map<String, Object> map = userService.login(user.getUsername(), user.getPassword());
        return R.ok().data(map);
    }

    @PostMapping("/register")
    public R register(@RequestBody User user){
        System.out.println("注册业务");
        Map<String, Object> map = userService.register(user);
        if (map == null) {
            //注册失败
            return R.error();
        }
        //注册成功
        return R.ok("注册成功!").data(map);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        Object userDetail = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userDetail instanceof UserDetails) {
            SecurityContextHolder.clearContext();
            //刷新token，让token失效，确保只能通过下次登陆获得的token进行接口访问
            //否则会造成，该token仍然能用于其他服务器即使已经注销！
            //TODO 销回JWT（分布式）
        }
        try{
            userService.delUserCache((UserDetail) userDetail);
        }catch (Exception e){
            new CustomException(HttpStatus.HTTP_OK,"请刷新页面");
        }
        return R.ok().message("退出成功！");
    }

    @GetMapping("/info")
    public R getUserInfo(){
        Object userDetail = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userDetail instanceof UserDetails) {
            User user = ((UserDetail) userDetail).getUser();
            UserVo userVo = new UserVo();
            BeanUtil.copyProperties(user,userVo);
            UserRole userRole = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
            userVo.setRoleId(userRole.getRoleId());
            userVo.setPassword("");
            return R.ok().data("userInfo",userVo);
        }else {
            return R.error().message("无此用户");
        }
    }

}
